var canvas = document.querySelector('#snakeArea')

//获取画笔
var ctx = canvas.getContext('2d');
//将画布的宽度调整为和css设置的宽高一致,避免出现放大效果
canvas.width = 600;
canvas.height = 360;

//蛇的数组
var headDir = 2; //0下  1上  2右 3左
var snakeArr = [new SnakePart(1, 0,headDir,-1), new SnakePart(0, 0,headDir,0)];
//用于保存头部所走过的运动轨迹
var tracks = [];

//食物坐标
var foodLocation = {x:-1, y:-1};

//用于保存尾部最近一个位置，为贪吃蛇生长做准备
var toAdd ={};

//控制蛇的速度，以毫秒为单位
var speed = 400;
//表示游戏结束
var GameOver = false;
//分数
var GameScore = '0000';

//时间
var GameTime = 00;

//在js中记载需要绘制的贪吃蛇
var headimg = document.createElement('img');
var bodyimg = document.createElement('img');
var footimg = document.createElement('img');
var foodimg = document.createElement('img');
//在js中，给图片元素设置src属性，浏览器就会自动加载该图片到内存中，js可以操作
headimg.src = './image/head.png';
bodyimg.src = './image/body.png';
footimg.src = './image/foot.png';
foodimg.src = './image/egg.png';

//在图片加载完成之后再绘制
//加载onload
headimg.onload = function () {
    footimg.onload = function () {
        bodyimg.onload = function () {
            drawsnake();
        }

    }
}

foodimg.onload = function () {
    createRandomFood();
    drawFood();
}

//绘制贪吃蛇
function drawsnake() {
    //绘制贪吃蛇的向下部分
    //将40*40的贪吃蛇，缩小一半，显示在画布上20*20
    var head = snakeArr[0];
    var foot = snakeArr[snakeArr.length - 1];
    //drawImage(img对象，图片绘制区域的左上角x,y,绘制宽度，高度，画布绘制区域的x,y,绘制宽度，高度)
    ctx.drawImage(headimg, headDir * 40, 0, 40, 40, head.x * 20, head.y * 20, 20, 20);
    ctx.drawImage(footimg, foot.dir * 40, 0, 40, 40, foot.x * 20, foot.y * 20, 20, 20);
    //绘制蛇的身体
    for(var i=1;i<snakeArr.length-1;i++){
        ctx.drawImage(bodyimg, 0, 0, 40, 40, snakeArr[i].x * 20, snakeArr[i].y * 20, 20, 20);
    }
}

//给页面设置键盘监听事件，只要按下键盘上的某个键，就会执行onkeydown指定的代码
document.body.onkeydown = function (e) {
    // console.log(e.keyCode);
    switch (e.keyCode) {
        case 38:
            console.log('up');
            headDir = 1;
            break;
        case 40:
            console.log('down');
            headDir = 0;
            break;
        case 37:
            console.log('left');
            headDir = 3;
            break;
        case 39:
            console.log('right');
            headDir = 2;
            break;
    }
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    move();
    eat();
    //console.log(snakeArr);
    drawsnake();
    drawFood();


}

//定时器
function start(){
    timer = setInterval(interval,speed);

    //播放背景音乐
    document.querySelector("#bgmusic").play();

}

//暂停游戏
function pause(){
    clearInterval(timer);
    timer = -1;
    GameOver = false;
    document.querySelector("#bgmusic").pause();
}

//设置定时器，不断的移动
function interval() {
    if(!GameOver){
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        move();
        //console.log(snakeArr);
        eat();
        out();
        drawsnake();
        drawFood();
        showScore();
        showTime();
    }else{
        //暂停游戏
        pause();
        
        //播放游戏结束音乐
        document.querySelector("#overmusic").play();
        //暂停背景音乐
        document.querySelector("#overmusic").pause();

        //显示游戏结束图片
        document.querySelector("#gameover").className = 'over'
        // alert("游戏结束");    
    }

}


function move() {
    //把头部当前位置加入到track数组中
    tracks.push(new Track(snakeArr[0].x,snakeArr[0].y,headDir));
    // console.log(tracks);

    //头部移动
    switch (headDir) {
        case 0:
            //往下移动
            snakeArr[0].y++;
            break;
        case 1:
            //往上移动
            snakeArr[0].y--;
            break;
        case 2:
            //往右移动
            snakeArr[0].x++;
            break;
        case 3:
            //往左移动
            snakeArr[0].x--;
            break;

    }

    //身体移动，其他部分跟着运动轨迹走，尾部位置保存到toAdd中
    var foot = snakeArr[snakeArr.length-1];
    toAdd = new SnakePart(foot.x, foot.y, foot.dir,foot.next);
    for(var i = 1; i < snakeArr.length; i++){
        var s = snakeArr[i];
        var next = tracks[s.next]
        s.x = next.x;
        s.y = next.y;
        s.dir =next.dir;
        s.next ++;

    }
}

//贪吃蛇生长
function createRandomFood(){
    var x = parseInt(Math.random()*30);
    var y = parseInt(Math.random()*18);
    foodLocation.x = x;
    foodLocation.y = y;
}
function drawFood(){
    ctx.drawImage(foodimg, 0, 0, 40, 40, foodLocation.x*20,foodLocation.y*20, 20, 20);
}
//判断是否可以吃食物
function eat(){
    //头部的位置和食物的位置是否一致
    var head = snakeArr[0];
    // console.log(head);
    // console.log(foodLocation);

    if(head.x == foodLocation.x && head.y == foodLocation.y){
        //贪吃蛇生长
        snakeArr.push(toAdd)
        //重新绘制食物
        createRandomFood();
        //播放音乐
        document.querySelector("#addmusic").play();
        //分数加1000
        GameScore = parseInt(GameScore)+1000;
    }

}

//出界
function out(){
    //是否出界
    x = snakeArr[0].x;
    y = snakeArr[0].y;
    if(x < 0 || y < 0 || x>=30 || y>=18){
        GameOver = true;
    }

    //是否和自己相遇
    var head = snakeArr[0];
    for(var i=1;i<snakeArr.length;i++){
        var s = snakeArr[i];
        if(head.x == s.x && head.y == s.y){
            GameOver = true;
            return;
        }
    }
}


//音乐

//显示分数
function showScore(){
    document.querySelector("#gamescore").innerHTML = GameScore;
}

//显示时间
function showTime(){
    GameTime += speed / 1000;
    document.querySelector("#gametime").innerHTML = parseInt(GameTime);
}